package org.hxyjs.dao.impl;

import org.hxyjs.dao.ProgrammeDao;
import org.hxyjs.entity.Programme;
import org.hxyjs.mapper.ProgrammeMapper;
import org.hxyjs.page.PageInfo;
import org.hxyjs.utils.GenNumTools;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Repository("programmeDao")//一般实现类不会直接生成默认对象名 而是使用 接口的默认对象名
public class ProgrammeDaoImpl implements ProgrammeDao {
    @Resource //autowired 会装配能够直接扫描到的对象  resource spring容器运行的时候才找到需要的对象  注入
    private ProgrammeMapper programmeMapper;

    //查询全部
    public List<Programme> getAllProgrammes() throws Exception {
        return programmeMapper.selectByExample(null);
    }

    //按主键查询
    @Override
    public Programme getProgrammeByPrno(String prno) throws Exception {
        return programmeMapper.selectByPrimaryKey(prno);
    }

    //分页查询
    @Override
    public List<Programme> getProgrammeByPage(PageInfo pageInfo) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("currPage", pageInfo.getCurrPage());
        map.put("pageSize", pageInfo.getPageSize());
        int itemCount = (int) programmeMapper.countByExample(null);
        pageInfo.setItemCount(itemCount);
        return programmeMapper.getProgrammesByPage(map);
    }

    //删除
    @Override
    public Integer deleteProgrammeByPrno(String prno) {
        return programmeMapper.deleteByPrimaryKey(prno);
    }

    //修改
    @Override
    public Integer updateProgrammeByPrno(Programme programme) {
        return programmeMapper.updateByPrimaryKey(programme);
    }


    //增加
    @Override
    public Integer addProgramme(Programme programme) {
        programme.setPrno(initId());
        return programmeMapper.insertSelective(programme);
    }

    public String initId() {
        String maxPrno = programmeMapper.getMaxPrno();
        maxPrno = Optional.ofNullable(maxPrno).orElse("0000");
        return GenNumTools.initId("pr", 4, maxPrno);
    }


}